// personal-center.js
const app = getApp();

Page({
  data: {
    userInfo: {
      nickName: '',
      avatarUrl: '',
      level: '普通用户',
      memberDays: 0
    },
    isLoggedIn: false,
    stats: {
      favorites: 0,
      history: 0,
      points: 0,
      coupons: 0
    },
    healthData: {
      calories: 0,
      protein: 0,
      carbs: 0,
      fat: 0
    },
    showHealthChart: false,
    healthChartData: []
  },

  onLoad: function() {
    // 检查登录状态
    this.checkLoginStatus();
  },

  onShow: function() {
    // 页面显示时刷新数据
    this.checkLoginStatus();
    this.loadUserStats();
    this.loadHealthData();
  },

  // 检查登录状态
  checkLoginStatus: function() {
    const userInfo = wx.getStorageSync('userInfo');
    const token = wx.getStorageSync('token');
    
    if (userInfo && token) {
      this.setData({
        userInfo: userInfo,
        isLoggedIn: true
      });
    } else {
      // 模拟用户数据
      this.setData({
        userInfo: {
          nickName: '美食爱好者',
          avatarUrl: '../../images/default-avatar.png',
          level: '普通用户',
          memberDays: 0
        },
        isLoggedIn: false
      });
    }
  },

  // 加载用户统计数据
  loadUserStats: function() {
    // 这里应该调用API获取数据，现在使用模拟数据
    const mockStats = {
      favorites: 12,
      history: 28,
      points: 356,
      coupons: 3
    };
    
    this.setData({
      stats: mockStats
    });
  },

  // 加载健康数据
  loadHealthData: function() {
    // 模拟健康数据
    const mockHealthData = {
      calories: 1850,
      protein: 85,
      carbs: 230,
      fat: 58
    };
    
    // 模拟图表数据（最近7天）
    const chartData = [];
    const today = new Date();
    for (let i = 6; i >= 0; i--) {
      const date = new Date(today);
      date.setDate(date.getDate() - i);
      const day = date.getDate();
      chartData.push({
        date: `${day}日`,
        calories: Math.floor(Math.random() * 500) + 1500,
        protein: Math.floor(Math.random() * 30) + 70,
        carbs: Math.floor(Math.random() * 50) + 200,
        fat: Math.floor(Math.random() * 20) + 50
      });
    }
    
    this.setData({
      healthData: mockHealthData,
      healthChartData: chartData
    });
  },

  // 初始化健康数据图表
  initHealthChart: function() {
    if (!this.data.healthChartData || this.data.healthChartData.length === 0) return;
    
    // 使用微信小程序canvas API绘制图表
    const ctx = wx.createCanvasContext('healthChart');
    const chartWidth = wx.getSystemInfoSync().windowWidth - 40;
    const chartHeight = 400;
    
    // 设置图表尺寸
    ctx.canvas.width = chartWidth;
    ctx.canvas.height = chartHeight;
    
    // 绘制坐标轴
    ctx.setStrokeStyle('#e0e0e0');
    ctx.setLineWidth(1);
    
    // X轴
    ctx.beginPath();
    ctx.moveTo(50, chartHeight - 50);
    ctx.lineTo(chartWidth - 20, chartHeight - 50);
    ctx.stroke();
    
    // Y轴
    ctx.beginPath();
    ctx.moveTo(50, 50);
    ctx.lineTo(50, chartHeight - 50);
    ctx.stroke();
    
    // 绘制数据点和连线
    const dataPoints = this.data.healthChartData;
    const maxCalories = Math.max(...dataPoints.map(item => item.calories)) * 1.1;
    const xStep = (chartWidth - 70) / (dataPoints.length - 1);
    
    // 绘制卡路里数据
    ctx.setStrokeStyle('#ff6b00');
    ctx.setLineWidth(3);
    ctx.beginPath();
    
    dataPoints.forEach((item, index) => {
      const x = 50 + index * xStep;
      const y = chartHeight - 50 - (item.calories / maxCalories) * 280;
      
      if (index === 0) {
        ctx.moveTo(x, y);
      } else {
        ctx.lineTo(x, y);
      }
      
      // 绘制数据点
      ctx.setFillStyle('#ff6b00');
      ctx.beginPath();
      ctx.arc(x, y, 4, 0, 2 * Math.PI);
      ctx.fill();
      
      // 绘制X轴标签
      ctx.setFontSize(12);
      ctx.setFillStyle('#999');
      ctx.fillText(item.date, x - 15, chartHeight - 30);
    });
    
    ctx.stroke();
    
    // 绘制图例
    ctx.setFillStyle('#ff6b00');
    ctx.fillRect(chartWidth - 120, 20, 10, 10);
    ctx.setFontSize(12);
    ctx.setFillStyle('#666');
    ctx.fillText('卡路里', chartWidth - 100, 30);
    
    // 绘制Y轴刻度
    ctx.setFontSize(12);
    ctx.setFillStyle('#999');
    for (let i = 0; i <= 3; i++) {
      const y = chartHeight - 50 - (i / 3) * 280;
      const value = Math.floor((i / 3) * maxCalories);
      
      ctx.beginPath();
      ctx.moveTo(45, y);
      ctx.lineTo(50, y);
      ctx.stroke();
      
      ctx.fillText(value, 10, y + 5);
    }
    
    ctx.draw();
  },

  // 登录
  login: function() {
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        const userInfo = res.userInfo;
        
        // 模拟登录成功，保存用户信息
        wx.setStorageSync('userInfo', userInfo);
        wx.setStorageSync('token', 'mock-token-' + Date.now());
        
        // 更新用户等级和会员天数
        userInfo.level = '普通用户';
        userInfo.memberDays = 0;
        
        this.setData({
          userInfo: userInfo,
          isLoggedIn: true
        });
        
        wx.showToast({
          title: '登录成功',
          icon: 'success'
        });
      },
      fail: () => {
        wx.showToast({
          title: '登录失败',
          icon: 'none'
        });
      }
    });
  },

  // 退出登录
  logout: function() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除本地存储的用户信息
          wx.removeStorageSync('userInfo');
          wx.removeStorageSync('token');
          
          this.setData({
            userInfo: {
              nickName: '',
              avatarUrl: '',
              level: '普通用户',
              memberDays: 0
            },
            isLoggedIn: false,
            stats: {
              favorites: 0,
              history: 0,
              points: 0,
              coupons: 0
            }
          });
          
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          });
        }
      }
    });
  },

  // 跳转到用户信息页面
  navigateToUserInfo: function() {
    if (!this.data.isLoggedIn) {
      this.login();
      return;
    }
    wx.navigateTo({
      url: '/pages/user-setting/user-setting'
    });
  },

  // 跳转到设置页面
  navigateToSetting: function() {
    wx.navigateTo({
      url: '/pages/user-setting/user-setting'
    });
  },

  // 跳转到收藏页面
  navigateToFavorites: function() {
    if (!this.data.isLoggedIn) {
      this.login();
      return;
    }
    wx.navigateTo({
      url: '/pages/favorites/favorites'
    });
  },

  // 跳转到历史记录页面
  navigateToHistory: function() {
    if (!this.data.isLoggedIn) {
      this.login();
      return;
    }
    wx.navigateTo({
      url: '/pages/history/history'
    });
  },

  // 跳转到购物清单页面
  navigateToShoppingList: function() {
    if (!this.data.isLoggedIn) {
      this.login();
      return;
    }
    wx.navigateTo({
      url: '/pages/shopping-list/shopping-list'
    });
  },

  // 跳转到营养分析页面
  navigateToNutritionAnalysis: function() {
    if (!this.data.isLoggedIn) {
      this.login();
      return;
    }
    // 显示健康数据图表
    this.setData({
      showHealthChart: true
    });
    
    // 延迟初始化图表，确保canvas已渲染
    setTimeout(() => {
      this.initHealthChart();
    }, 100);
  },

  // 跳转到会员中心
  navigateToMember: function() {
    wx.navigateTo({
      url: '/pages/member/member'
    });
  },

  // 跳转到积分页面
  navigateToPoints: function() {
    if (!this.data.isLoggedIn) {
      this.login();
      return;
    }
    wx.navigateTo({
      url: '/pages/points/points'
    });
  },

  // 跳转到优惠券页面
  navigateToCoupons: function() {
    if (!this.data.isLoggedIn) {
      this.login();
      return;
    }
    wx.navigateTo({
      url: '/pages/coupons/coupons'
    });
  },

  // 跳转到意见反馈页面
  navigateToFeedback: function() {
    wx.navigateTo({
      url: '/pages/feedback/feedback'
    });
  },

  // 跳转到帮助中心
  navigateToHelp: function() {
    wx.navigateTo({
      url: '/pages/help/help'
    });
  },

  // 跳转到关于我们页面
  navigateToAbout: function() {
    wx.navigateTo({
      url: '/pages/about/about'
    });
  },

  // 关闭健康数据图表
  closeHealthChart: function() {
    this.setData({
      showHealthChart: false
    });
  },

  // 返回上一页
  onBack: function() {
    wx.navigateBack();
  }
})